<template>
  <div>
    <el-button type="primary" @click="createTask(tform)">
      <el-icon :size="14">
        <plus />
      </el-icon>
      创建任务
    </el-button>
  </div>
  <el-divider />
  <!--任务列表-->
  <el-table :data="tasks.records" border style="width: 100%">
    <el-table-column prop="name" label="名称" width="380" />
    <el-table-column prop="created" label="创建时间" width="280" />
    <el-table-column label="总体进度" width="280" >
      <template #default="scope">
        <el-progress :percentage="scope.row.completed/scope.row.total*100" status="success" :text-inside="true" :stroke-width="24"/>
      </template>
    </el-table-column>
    <el-table-column label="状态" width="280" >
      <template #default="scope">
        <el-select v-model="scope.row.statu" size="small" @change="chgStatu(scope.row)">
          <el-option
              v-for="item in status"
              :key="item.statu"
              :label="item.name"
              :value="item.statu"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="danger" size="small" plain @click="delTask(scope.row.id)">
          <el-icon :size="14">
            <close />
          </el-icon>
          删除任务
        </el-button>
        <el-button type="info" size="small" plain @click="getDepartProgress(scope.row.id)">
          <el-icon :size="14">
            <tickets />
          </el-icon>
          部门列表
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--任务管理对话框-->
  <el-dialog v-model="dlgCreateTask" title="创建工资任务" width="50%" :close-on-click-modal="false">
    <el-form :inline="true" :model="taskForm" :rules="rules" ref="tform">
      <el-form-item label="名称" prop="name">
        <el-input v-model="taskForm.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="截至时间" prop="endTime">
        <el-date-picker v-model="taskForm.endTime" type="datetime" placeholder="截至时间" />
      </el-form-item>
      <el-form-item label="绩效总额：">
        {{summary}}元
      </el-form-item>
    </el-form>
    <el-table :data="taskForm.departs" height="450" style="width: 100%">
      <el-table-column prop="id" label="部门编号" width="180" />
      <el-table-column prop="name" label="部门名称" width="180" />
      <el-table-column label="部门绩效总额" >
        <template #default="scope">
          <el-input-number v-model="scope.row.bonus" size="small" :min="0" :max="100000" :precision="2" :controls="false"/>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dlgCreateTask = false">取消</el-button>
        <el-button type="primary" @click="submitForm(tform)">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!--各部门进度对话框-->
  <el-dialog v-model="dlgDepartProgress" title="各部门进度" width="50%">
    <el-table :data="departTasks" max-height="450" style="width: 100%">
      <el-table-column prop="id" label="部门编号" width="100"> </el-table-column>
      <el-table-column prop="departName" label="部门名称" width="240"> </el-table-column>
      <el-table-column prop="itemCount" label="部门人数" width="120"> </el-table-column>
      <el-table-column prop="bonus" label="绩效总额" width="180"> </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          <el-button
              :type="status.find(st => st.statu == scope.row.statu).type"
              plain size="small">
            {{status.find(st => st.statu == scope.row.statu).name}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button type="text" size="small" @click="resetDepartTask(scope.row.id)" :disabled="scope.row.statu!==1">重置部门任务</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup>
import {reactive, ref, onMounted, computed} from "vue";
import {changeStatus, deleteTask, getDepartList, getTaskList, saveTask} from "@/api/wage";
import _ from 'lodash';
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {Plus, Tickets} from "@element-plus/icons-vue";
import {getDepartTasks, getPagedTasks, resetDepartTaskById} from "../../api/wage";

  // 任务列表
  const tasks = ref({
    current: 1,
    records: [],
    size: 10,
    pages: 0,
    total: 0
  })
  // 对话框显示
  const dlgCreateTask = ref(false)
  const dlgDepartProgress = ref(false)
  const selectTest = ref(1)

  // 任务表单
  const taskForm = reactive({
    name: '',
    endTime: null,
    departs: []
  })

  // 表单对象
  const tform = ref(null)

  // 部门任务
  const departTasks = ref([])

  // 验证规则
  const rules = {
    name: [
      { required: true, message: '请输入任务名称', trigger: 'blur' },
      { min: 1, max: 20, message: '长度在1-20字符之间', trigger: 'blur' },
    ],
    endTime: [
      { required: true, message: '请选择截至时间', trigger: 'blur'}
    ]
  }

  // 状态信息
  const status = [
    { statu: 0, name: '初始化', type: 'primary' },
    { statu: 1, name: '进行中', type: 'warning' },
    { statu: 2, name: '已结束' , type: 'success'},
  ]

  // 加载数据
  onMounted(() => {
    getTasks()
  })

  // 获取任务列表
  const getTasks = function () {
    const tsk = tasks.value
    // getTaskList(tsk.current, tsk.size).then(res => {
    //   tasks.value = res.data
    // })
    getPagedTasks(tsk.current, tsk.size).then(res => {
      tasks.value = res.data
    })
  }

  // 创建任务
  const createTask = function (tform) {
    // 重置表单
    if(tform) {
      tform.resetFields()
    }
    // 获取部门列表
    getDepartList().then(res => {
      taskForm.departs = res.data
      dlgCreateTask.value = true
    })
  }

  // 计算工资总额
  const summary = computed(() => {
    let sum = 0
    _.forEach(taskForm.departs, function(dept) {
      sum += dept.bonus
    })
    return sum
  })

  // 保存任务
  const submitForm = async (tform) => {
    if(!tform) return
    await tform.validate((valid, fileds) => {
      if(valid) {
        ElMessageBox.confirm('你正在保存创建的任务. 继续?','提示',
            { confirmButtonText: '保存', cancelButtonText: '取消', type: 'warning', }
        ).then(() => {
          const inst = ElLoading.service({ fullscreen: true })
          saveTask(taskForm).then(res => {
            ElMessage.success("创建成功")
            getTasks()
            dlgCreateTask.value = false
            inst.close()
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '保存取消',
          })
        })
      }
    })
  }

  // 改变任务状态
  const chgStatu = (task) => {
    ElMessageBox.confirm('修改任务状态可能重置任务，是否继续?','提示',{
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {
      const inst = ElLoading.service({ fullscreen: true })
      changeStatus(task.id, task.statu).then(res => {
        inst.close()
        getTasks()  // 重新获取列表
        ElMessage.success('修改成功')
      })
    }).catch(() => {
      ElMessage.info('取消更改')
      getTasks()
    })
  }

  // 删除任务
  const delTask = (taskId) => {
    ElMessageBox.confirm('你正在删除任务. 确认?','警告', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'error', }).then(() => {
      deleteTask(taskId).then(res => {
        ElMessage({ type: 'success', message: '删除成功', })
        getTasks()
      })
    }).catch(() => {
      ElMessage({ type: 'info', message: '取消删除', })
    })
  }

  // 显示各部门进度
  const getDepartProgress = (taskId) => {
    getDepartTasks(taskId).then(res => {
      departTasks.value = res.data
      dlgDepartProgress.value = true
    })
  }

  const resetDepartTask = (departTaskId) => {
    ElMessageBox.confirm('重置任务后将清除原来的设置，是否继续?',
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          resetDepartTaskById(departTaskId).then(res => {
            ElMessage.info(res.msg)
          })
        })
  }
</script>

<style scoped>
</style>